package com.hundsun.aitest.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hundsun.aitest.common.Result;
import com.hundsun.aitest.model.ai.AutoCase;
import com.hundsun.aitest.model.blade.TestCaseRequest;
import com.hundsun.aitest.model.blade.Variable;
import com.hundsun.aitest.service.BaoSongDBService;
import com.hundsun.aitest.service.CheckCaseService;
import com.hundsun.aitest.service.TestCasesService;
import com.hundsun.aitest.util.TaskProgress;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

@Controller
@Slf4j
public class CheckCaseController {
    final String DEFAULT_API_TOKEN = "HR_oSn4k1y9NpsfcT7UWvt7jQQ-t8kTG3EH8oOD3LgdKmf0cNBFii1PH9NHsDaBmq1WuFCH2Tn5R0CZ8IWEyKg";
    final String DEFAULT_ACCOUNT = "yangjf48332";
    @Autowired
    private CheckCaseService checkCaseService;

    @Autowired
    private TestCasesService testCasesService;

    @Autowired
    private BaoSongDBService baoSongDBService;

    // 任务进度存储
    private final ConcurrentHashMap<String, TaskProgress> taskProgressMap;

    @Autowired
    public CheckCaseController(ConcurrentHashMap<String, TaskProgress> taskProgressMap) {
        this.taskProgressMap = taskProgressMap;
    }

    @PostMapping("/checkCaseByCheckCode")
    @ResponseBody
    public Result<String> checkCaseByCheckCode(@RequestBody Map<String, String> requestBody) {
        Result<String> result = new Result<>();

        try {
            // 从请求体中获取数据
            String checkCodesStr = requestBody.get("checkCode");
            if (checkCodesStr == null || checkCodesStr.isEmpty()) {
                throw new IllegalArgumentException("Check codes cannot be null or empty.");
            }

            String[] checkCodesArray = checkCodesStr.split(";");
            List<String> checkCodes = Arrays.asList(checkCodesArray);

            String apiToken = requestBody.getOrDefault("apiToken", DEFAULT_API_TOKEN);
            String account = requestBody.getOrDefault("account", DEFAULT_ACCOUNT);
            String nodePath = requestBody.get("nodePath");

            // 生成任务ID
            String taskId = UUID.randomUUID().toString();
            taskProgressMap.put(taskId, new TaskProgress(checkCodes.size()));
            // 异步处理用例
            CompletableFuture.runAsync(() -> processAndUploadCases(taskId, checkCodes, nodePath, result, apiToken, account));

            // 立即返回“用例生成中”
            result.setSuccess(true);
            result.setData(taskId);

        } catch (Exception e) {
            log.error("Error generating check cases for checkCode request", e);
            result.setSuccess(false);
            result.setData("Failed to generate check cases: " + e.getMessage());
        }
        return result;
    }

    @PostMapping("/checkCaseByParent")
    @ResponseBody
    public Result<String> checkCaseByParent(@RequestBody Map<String, String> requestBody) {
        Result<String> result = new Result<>();

        try {
            // 从请求体中获取数据
            String parentStr = requestBody.get("parent");
            JSONArray reportListResult = baoSongDBService.getReportList(parentStr);
            // 创建一个List来存储所有的REPORT_CODE值
            List<String> reportCodeList = new ArrayList<>();
            // 遍历JSONArray，提取每个对象的REPORT_CODE值并添加到List中
            for (int i = 0; i < reportListResult.size(); i++) {
                JSONObject report = reportListResult.getJSONObject(i);
                String reportCode = report.getString("REPORT_CODE");
                reportCodeList.add(reportCode);
            }


            List<String> checkCodes = new ArrayList<>();
            for (String reportCode : reportCodeList) {
                JSONArray results = baoSongDBService.getCheckRules(reportCode);
                checkCodes.addAll(results.toJavaList(String.class));
            }

            String apiToken = requestBody.getOrDefault("apiToken", DEFAULT_API_TOKEN);
            String account = requestBody.getOrDefault("account", DEFAULT_ACCOUNT);
            String nodePath = requestBody.get("nodePath");

            // 生成任务ID
            String taskId = UUID.randomUUID().toString();
            taskProgressMap.put(taskId, new TaskProgress(checkCodes.size()));

            // 异步处理用例
            CompletableFuture.runAsync(() -> processAndUploadCases(taskId, checkCodes, nodePath, result, apiToken, account));
            // 立即返回“用例生成中”
            result.setSuccess(true);
            result.setData(taskId);


        } catch (Exception e) {
            log.error("Error generating check cases for reportCode request", e);
            result.setSuccess(false);
            result.setData("Failed to generate check cases: " + e.getMessage());
        }
        return result;

    }
    @PostMapping("/checkCaseByReportCode")
    @ResponseBody
    public Result<String> checkCaseByReportCode(@RequestBody Map<String, String> requestBody) {
        Result<String> result = new Result<>();

        try {
            // 从请求体中获取数据
            String reportCodesStr = requestBody.get("reportCode");
            if (reportCodesStr == null || reportCodesStr.isEmpty()) {
                throw new IllegalArgumentException("Report codes cannot be null or empty.");
            }

            String[] reportCodesArray = reportCodesStr.split(";");
            List<String> reportCodes = Arrays.asList(reportCodesArray);
            List<String> checkCodes = new ArrayList<>();
            for (String reportCode : reportCodes) {
                JSONArray results = baoSongDBService.getCheckRules(reportCode);
                checkCodes.addAll(results.toJavaList(String.class));
            }

            String apiToken = requestBody.getOrDefault("apiToken", DEFAULT_API_TOKEN);
            String account = requestBody.getOrDefault("account", DEFAULT_ACCOUNT);
            String nodePath = requestBody.get("nodePath");

            // 生成任务ID
            String taskId = UUID.randomUUID().toString();
            taskProgressMap.put(taskId, new TaskProgress(checkCodes.size()));

            // 异步处理用例
            CompletableFuture.runAsync(() -> processAndUploadCases(taskId, checkCodes, nodePath, result, apiToken, account));

            // 立即返回“用例生成中”
            result.setSuccess(true);
            result.setData(taskId);


        } catch (Exception e) {
            log.error("Error generating check cases for reportCode request", e);
            result.setSuccess(false);
            result.setData("Failed to generate check cases: " + e.getMessage());
        }
        return result;
    }

    private void processAndUploadCases(String taskId, List<String> codes, String nodePath, Result<String> result, String apiToken, String account) {
        List<AutoCase> checkCases = new ArrayList<>();
        StringBuilder uploadResults = new StringBuilder();

        for (String code : codes) {
            try {
                // 生成自动化用例结构
                AutoCase autoCase = checkCaseService.generateSingleCheckCase(code);

                if (autoCase == null) {
                    log.error("解析用例失败，勾稽编号: {}", code);
                    continue;
                }

                String repotCode = code.split("\\.")[0];
                JSONArray reportInfo = baoSongDBService.getReportInfo(repotCode);

                // 根据 code 构建当前路径
                String currentVariablePath = nodePath + "/" + baoSongDBService.getDirectory(code) + "/" + repotCode + "-" + reportInfo.getJSONObject(0).getString("REPORT_NAME") + "/" + "参数";
                String currentCasePath = nodePath + "/" + baoSongDBService.getDirectory(code) + "/" + repotCode + "-" + reportInfo.getJSONObject(0).getString("REPORT_NAME") + "/" + code;

                // 构建参数
                Variable vResult = testCasesService.buildVariableRequest(apiToken, account, currentVariablePath, repotCode);
                String vUploadResult = testCasesService.uploadVarible(vResult);
                uploadResults.append(vUploadResult).append("\n");

                // 构建 TestCaseRequest
                TestCaseRequest testCaseRequest = testCasesService.buildTestCaseRequest(apiToken, account, currentCasePath, autoCase, code);
                String uploadResult = testCasesService.uploadTestCase(testCaseRequest);
                uploadResults.append(uploadResult).append("\n");

                // 更新任务进度
                updateTaskProgress(taskId, "成功处理用例: " + code);
            } catch (Exception e) {
                log.error("处理用例时发生错误，勾稽编号: {}", code, e);
                updateTaskProgress(taskId, "错误处理用例: " + code);
            }
        }

        // 设置最终结果
        result.setSuccess(true);
        result.setData(uploadResults.toString());

    }


    private synchronized void updateTaskProgress(String taskId, String message) {
        TaskProgress progress = taskProgressMap.get(taskId);
        if (progress != null) {
            progress.incrementCompleted();
            int percent = (int) ((double) progress.getCompleted() / progress.getTotal() * 100);
            log.info("任务 {} 进度更新: {}% - {}", taskId, percent, message);
            progress.setMessage(message);
        }
    }

}
